/*
 *  Copyright 2011 Alexey Andreev.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.xthl.core;

import org.nop.templating.Template;
import org.nop.util.Injected;
import org.xthl.core.api.UserDetails;
import org.xthl.core.api.UserLogic;
import org.xthl.core.lang.PagesBundle;
import org.xthl.core.view.LoginBlockView;
import org.xthl.core.view.LoginForm;
import org.xthl.core.view.LogoutBlockView;
import org.xthl.core.view.LogoutForm;

/**
 *
 * @author Alexey Andreev
 */
public class LoginBlock extends AbstractBlock {
    private UserLogic logic;
    
    @Injected
    public LoginBlock(UserLogic logic) {
        this.logic = logic;
    }

    @Override
    public boolean isVisible() {
        return true;
    }

    @Override
    public Template getView() {
        UserDetails user = logic.getCurrentUser(); 
        if (user == null) {
            LoginForm form = obtainForm(LoginForm.class, "");
            form.setLastUrl(services.getRequestPath());
            return createView(LoginBlockView.class)
                    .setForm(form)
                    .setRegistrationAvailable(logic.checkPermission("user.create"));
        } else {
            LogoutForm form = obtainForm(LogoutForm.class, "");
            form.setBackUrl(services.getRequestPath());
            return createView(LogoutBlockView.class)
                    .setForm(form)
                    .setLogin(user.getLogin());
        }
    }

    @Override
    public Template getTitle() {
        return bundle(PagesBundle.class).enterBlock();
    }
}
